import shutil, os
import json

def createDirs(pathDir):
    #判断文件路径是否存在，如果不存在，则创建，此处是创建多级目录
    if not os.path.isdir(pathDir):
        os.makedirs(pathDir)
    return

def readJsonFile(path):
    '''
    path: xxx/xx.json
    '''
    # 读取JSON文件
    # with open(path, 'r') as file:
    #     data = json.loads(file)
    #     # 添加一个值
    #     #data['new_key'] = 'new_value'
    #     return data
    f = open(path, 'r', encoding='utf-8')
    if f:
        content = f.read()
        data = json.loads(content)
        f.close()
        return data
def writeJsonFile(path, data):
    # 写入JSON文件
    with open(path, 'w', encoding='utf-8') as file:
        content = json.dumps(data, ensure_ascii=False, indent=4)
        file.write(content)

#300_MulLinesMergeStep， 初始文件
def initFile(paramsPath,id, row, col):
    '''
   
    '''
    defaultFilePath = paramsPath+"\\"+id+"_MulLinesMergeStep.json"
    if(not os.path.exists(defaultFilePath)):
        print(defaultFilePath, " >>>> not exist")
        return
    
    mulParamsDirPath = paramsPath+"\\"+id+"_MulLinesMergeStep\\"
    createDirs(mulParamsDirPath)

    #mapping_config.json
    mapping = [
		{
			"file": "row1col1_0",
			"pos":[
				{"row": 100000, "col":1, "idx":0}
			]
		}
	]
    mapping_config = {}
    mapping_config['mapping'] = mapping
    if(not os.path.exists(mulParamsDirPath+"mapping_config.json")):
        print("mapping_config.json not exist, create")
        writeJsonFile(mulParamsDirPath+"mapping_config.json", mapping_config)
    else:
        print("mapping_config.json exist")
    mulParamsFilePath = []
    for r in range(1,row+1):
        for c in range(1,col+1):
            data = readJsonFile(defaultFilePath)
            if 'lineShitf1' in data:
                lineShift = data['lineShitf1']
                if 'x' in lineShift and 'y' in lineShift:
                    lineShift['x'] = 0
                    lineShift['y'] = 0

            paramsFile = mulParamsDirPath + "sn_row"+str(r)+"col"+str(c)+"_0sn_.json"
            writeJsonFile(paramsFile, data)
            mulParamsFilePath.append(paramsFile)
    return mulParamsDirPath

def updateJsonValue(jsonData, key, x, y):
    if key not in jsonData:
        print("key not exist: ", key)
        return
    lineShift = jsonData[key]
    if 'x' in lineShift and 'y' in lineShift:
        if x != None:
            lineShift['x'] = x
        if y != None:
            lineShift['y'] = y
    else:
        print("x, y not exist")
    return jsonData



#非通用
def updateFileParams(mulParamsDirPath,row,col, top, right, bottom, left):
    print(">>> ", top)
    print(">>> ", right)
    print(">>> ", bottom)
    print(">>> ", left)
    for r in range(1,row+1):
        for c in range(1,col+1):
            filePath = mulParamsDirPath + "sn_row"+str(r)+"col"+str(c)+"_0sn_.json"
            print("start update: ", filePath)
            data = readJsonFile(filePath)
            if c == 1:
                #上
                data = updateJsonValue(data, 'lineShitf1',x=None, y=top)
            if c == 2:
                #下
                data = updateJsonValue(data, 'lineShitf3',x=None, y=bottom)

            if r == 1 and (c==1 or c == 2):
                #右
                data = updateJsonValue(data, 'lineShitf2', x=right, y=None)
            if r == 4 and (c==1 or c == 2):
                #左
                data = updateJsonValue(data, 'lineShitf4', x=left, y=None)
            writeJsonFile(filePath, data)
    
    mapping_configPath = mulParamsDirPath+"mapping_config.json"
    data = readJsonFile(mapping_configPath)
    lineShift = {}
    lineShift['top'] = top
    lineShift['right'] = right
    lineShift['bottom'] = bottom
    lineShift['left'] = left
    data['edgeOffset'] = lineShift
    
    writeJsonFile(mapping_configPath, data)
    return
      
def run(modelPath,stepIdStr,top,right,bottom,left):
    '''
    用于四边方位固定，如AA区定位
    '''
    # modelPath = paramsDict["modelPath"]
    # stepIdStr = paramsDict["stepId"]
    # top = paramsDict["offsetTopValue"] 
    # right = paramsDict["offsetRightValue"]
    # bottom = paramsDict["offsetBottomValue"]
    # left = paramsDict["offsetLeftValue"]
    if modelPath == None or stepIdStr == None\
        or top == None or right == None or bottom == None or left == None:
        return -1
    row = 4
    col = 2
    paramsPath =modelPath + "\\Parameters"

    if(not os.path.exists(paramsPath)):
        print(paramsPath, " >>>> not exist")
        exit(0)

    print("modelPath: ", modelPath, "\nrow:" ,row)
    print("col: ", col)
    print("stepid: ", stepIdStr)
    if not os.path.isdir(paramsPath):
        return -1 
    
    mulParamsDirPath = initFile(paramsPath=paramsPath,id=stepIdStr,row=row,col=col)
    updateFileParams(mulParamsDirPath,row=row,col=col,top=top,right=right,bottom=bottom, left=left)
    return 1

class BiasData:
    top1 = 0
    top2 = 0
    right1 = 0
    right2 = 0
    bottom1 = 0
    bottom2 = 0
    left1 = 0
    left2 = 0
    def __init__(self,top1 = None,top2 = None,right1 = None,right2 = None,bottom1 = None,bottom2 = None,left1 = None,left2 = None):
        self.top1 = top1  
        self.top2 = top2  #小偏移
        self.left1 = left1 
        self.left2 = left2   #小偏移

        self.right1 = right1 
        self.right2 = right2  #小偏移
        self.bottom1 = bottom1 
        self.bottom2 = bottom2   #小偏移

    def showInfo(self):
        # 遍历类的属性（不包括方法）
        for attr_name in self.__dict__:
            if not attr_name.startswith('__'):  # 排除特殊方法和属性
                attr_value = getattr(self, attr_name)
                print(f"Attribute: {attr_name}, Value: {attr_value}")

def updateFileParams2(mulParamsDirPath,row,col, biasData):
    '''
    上下边一个step，左右边是一个step,用于水平垂直油墨
    '''
    for r in range(1,row+1):
        for c in range(1,col+1):
            filePath = mulParamsDirPath + "sn_row"+str(r)+"col"+str(c)+"_0sn_.json"
            print("start update: ", filePath)
            data = readJsonFile(filePath)
            if c == 1:
                #上水平油墨
                data = updateJsonValue(data, 'lineShitf1',x=None, y=biasData.top1)
                data = updateJsonValue(data, 'lineShitf3',x=None, y=biasData.top2)
            
            if r == 4 and (c==1 or c == 2):
                #左垂直油墨
                data = updateJsonValue(data, 'lineShitf2', x=biasData.left1, y=None)
                data = updateJsonValue(data, 'lineShitf4', x=biasData.left2, y=None)


            if c == 2:
                #下水平油墨
                data = updateJsonValue(data, 'lineShitf1',x=None, y=biasData.bottom1)
                data = updateJsonValue(data, 'lineShitf3',x=None, y=biasData.bottom2)
            if r == 1 and (c==1 or c == 2):
                #右
                data = updateJsonValue(data, 'lineShitf2', x=biasData.right1, y=None)
                data = updateJsonValue(data, 'lineShitf4', x=biasData.right2, y=None)
            writeJsonFile(filePath, data)
    
    mapping_configPath = mulParamsDirPath+"mapping_config.json"
    data = readJsonFile(mapping_configPath)
    lineShift = {}
    lineShift['top'] = biasData.top1
    lineShift['right'] = biasData.right1
    lineShift['bottom'] = biasData.bottom1
    lineShift['left'] = biasData.left1
    data['edgeOffset'] = lineShift
    
    writeJsonFile(mapping_configPath, data)
    return
      
def run2(modelPath,stepIdStr,biasData):
    '''
    上下边一个step，左右边是一个step,用于水平垂直油墨
    '''
    # modelPath = paramsDict["modelPath"]
    # stepIdStr = paramsDict["stepId"]
    # top = paramsDict["offsetTopValue"] 
    # right = paramsDict["offsetRightValue"]
    # bottom = paramsDict["offsetBottomValue"]
    # left = paramsDict["offsetLeftValue"]
    if modelPath == None or stepIdStr == None:
        return -1
    
    paramsPath =modelPath + "\\Parameters"

    if(not os.path.exists(paramsPath)):
        print(paramsPath, " >>>> not exist")
        return -1 
    if not os.path.isdir(paramsPath):
        return -1 

    row = 4
    col = 2
    print("modelPath: ", modelPath, "\nrow:" ,row)
    print("col: ", col)
    print("stepid: ", stepIdStr)
    
    mulParamsDirPath = initFile(paramsPath=paramsPath,id=stepIdStr,row=row,col=col)
    updateFileParams2(mulParamsDirPath,row=row,col=col,biasData=biasData)
    return 1

def testFunc():
    print("this is test")

def zhengLight_fei(modelPath):
    #正明非超
    #AA
    if 1:
        biasData = BiasData(top1=136,         top2=0, 
                            bottom1=-181,     bottom2=0, 
                            left1=159,     left2=0, 
                            right1=-152,    right2=0)
        run2(modelPath, "319",biasData=biasData)
    #油墨
    if 1:
        #水平油墨
        biasData = BiasData(top1=105,         top2=2, 
                            bottom1=-159,     bottom2=-2, 
                            left1=5,     left2=2, 
                            right1=-5,    right2=-2)
        run2(modelPath, "333",biasData=biasData)

        #垂直油墨
        biasData = BiasData(top1=119,         top2=0, 
                            bottom1=-169,     bottom2=0, 
                            left1=136,     left2=2, 
                            right1=-137,    right2=-2)
        run2(modelPath, "335",biasData=biasData)

def beiming_fei(modelPath):
    #背明
    #AA
    if 1:
        biasData = BiasData(top1=65,         top2=0, 
                            bottom1=-65,     bottom2=0, 
                            left1=15,     left2=0, 
                            right1=-20,    right2=0)
        run2(modelPath, "310",biasData=biasData)
    #油墨
    if 1:
        #水平油墨
        biasData = BiasData(top1=32,         top2=2, 
                            bottom1=-50,     bottom2=-2, 
                            left1=18,     left2=2, 
                            right1=-17,    right2=-2)
        run2(modelPath, "367",biasData=biasData)

        #垂直油墨
        biasData = BiasData(top1=0,         top2=0, 
                            bottom1=0,     bottom2=0, 
                            left1=-15,     left2=3, 
                            right1=20,    right2=-2)
        run2(modelPath, "351",biasData=biasData)


def zhengAn_fei(modelPath):
    #正暗
    #AA
    if 1:
        run(modelPath, "315",top= 118, right= -170, bottom= -197, left= 180)
    #油墨
    if 1:
        top = 115
        right = -142
        left = 148
        bottom= -175
        #油墨外侧
        run(modelPath, "313",top= 7, right= -5, bottom= -7, left= 5)

        #油墨内测
        run(modelPath, "329",top= 120, right= -138, bottom= -175, left= 148)

if __name__ == "__main__":  
    
    local = "正暗"
    modelName = "65inch_6450JAHAO"
    #modelPath = "E:\\workspace\\0_model\\0_shenzhenHuaxing_piantie-new\\65inch_6450JAHAO\\"+local+"\\model_"+local+"_"+modelName
    
    modelPath = "E:\\workspace\\0_model\\0_shenzhenHuaxing_piantie-new\\65inch_6450JAHAO\\正暗\\model_正暗_65inch_6450JAHAO"
    #beiming_fei(modelPath)
    #zhengLight_fei(modelPath)
    zhengAn_fei(modelPath)






